package com.lengxf.leetcode.a;

import java.util.Arrays;


public class Leetcode_mergingSort {


    /**
     * 归并排序
     * 先拆分后合并
     * 递归操作
     * By Lengxf 2023-09-26 17:41:13
     **/
    public static void main(String[] args) {
        int[] arr = GenerateArr.getArr(10);
        System.out.println("开始前 : " + Arrays.toString(arr));
        mergeSort(arr);
        System.out.println("排序完成 : " + Arrays.toString(arr));
    }

    private static void mergeSort(int[] arr) {
        int[] tmpArr = new int[arr.length];
        sort(arr, 0, arr.length - 1, tmpArr);
    }

    private static void sort(int[] arr, int left, int right, int[] tmpArr) {
        if (left >= right) {
            return;
        }
        int mid = left + (right - left) / 2;
        sort(arr, left, mid, tmpArr);
        sort(arr, mid + 1, right, tmpArr);
        merge(arr, left, right, tmpArr, mid);
    }

    private static void merge(int[] arr, int left, int right, int[] tmpArr, int mid) {
        int l = left;
        int r = mid + 1;
        int index = 0;
        while (l <= mid && r <= right) {
            if (arr[l] < arr[r]) {
                tmpArr[index++] = arr[l++];
            } else {
                tmpArr[index++] = arr[r++];
            }
        }
        while (l <= mid) {
            tmpArr[index++] = arr[l++];
        }
        while (r <= right) {
            tmpArr[index++] = arr[r++];
        }
        while (index >0) {
            arr[right--] = tmpArr[--index];
        }
    }


}
